from flask import Flask, request, render_template
from find_way import *
from read_file import *

app = Flask(__name__)
app.json.ensure_ascii = False
# api返回值是utf-8
lineDict = read_line()


@app.route('/')
def welcome():  # put application's code here
    address = "http://10.29.79.6:5000"
    return render_template('help.html', address=address)


@app.route('/api/get/way')
def find_way():
    # lineDict = read_line()
    start_station_name = request.args.get('start')
    end_station_name = request.args.get('end')
    result = find_whole_way(lineDict, start_station_name, end_station_name)
    return result


@app.route('/api/get/map')
def get_map():
    try:
        line_dict = lineDict  # 获取线路数据
        result = {"lines": []}

        for line_name in line_dict:
            line = line_dict[line_name]

            # 构建线路基本信息
            line_info = {
                "line_name": line.name,
                "is_loop": bool(line.isLoop),
                "dir1_first": line.dir1First,
                "dir1_last": line.dir1Last,
                "dir2_first": line.dir2First,
                "dir2_last": line.dir2Last,
                "gap_time": line.gapTime,
                "stations": []
            }

            # 处理站点信息
            for station_name in line.stations:
                station = line.stations[station_name]

                # 获取换乘线路信息
                transfers = []
                # 遍历当前线路的邻接线路信息
                for neighbor_line, transfer_stations in line.neighbours.items():
                    if station.name in transfer_stations:
                        transfers.append(neighbor_line)

                # 构建站点数据
                station_info = {
                    "name": station.name,
                    "is_transfer": len(transfers) > 0 or station.isTrans,
                    "transfers": transfers
                }

                line_info["stations"].append(station_info)

            result["lines"].append(line_info)

        return result

    except Exception as e:
        return {
            "error": "数据加载失败",
            "detail": str(e)
        }, 500


@app.route('/api/add/station', methods=['POST'])
def api_add_station():
    """ 添加站点接口 """
    try:
        data = request.get_json()
        required = ['line_name', 'station_name', 'front_station', 'distance']
        if not all(k in data for k in required):
            return {"success": False, "message": "缺少必要参数"}, 400

        result = add_station(
            line_name=data['line_name'],
            station_name=data['station_name'],
            front_station=data['front_station'],
            distance=int(data['distance']),
            line_dict=lineDict
        )
        return result if result['success'] else (result, 400)
    except Exception as e:
        return {"success": False, "message": str(e)}, 500


@app.route('/api/del/station', methods=['POST'])
def api_delete_station():
    """ 删除站点接口 """
    try:
        data = request.get_json()
        if 'line_name' not in data or 'station_name' not in data:
            return {"success": False, "message": "需要线路和站点名称"}, 400

        result = delete_station(
            line_name=data['line_name'],
            station_name=data['station_name'],
            line_dict=lineDict
        )
        status = 200 if result['success'] else 404
        return result, status
    except Exception as e:
        return {"success": False, "message": str(e)}, 500


@app.route('/api/add/line', methods=['POST'])
def api_add_line():
    """ 添加线路接口 """
    try:
        data = request.get_json()
        required = ['name', 'gap_time', 'speed', 'dir']
        if not all(k in data for k in required):
            print(data)
            return {"success": False, "message": "缺少必要参数"}, 400

        result = add_line(
            name=data['name'],
            gapTime=int(data['gap_time']),
            speed=float(data['speed']),
            dir=data['dir'],
            line_dict=lineDict
        )
        return result if result['success'] else (result, 400)
    except Exception as e:
        return {"success": False, "message": str(e)}, 500


@app.route('/api/del/line', methods=['POST'])
def api_delete_line():
    """ 删除线路接口 """
    try:
        data = request.get_json()
        if 'line_name' not in data:
            return {"success": False, "message": "需要线路名称"}, 400

        result = delete_line(
            line_name=data['line_name'],
            line_dict=lineDict
        )
        status = 200 if result['success'] else 404
        return result, status
    except Exception as e:
        return {"success": False, "message": str(e)}, 500

@app.route('/admin')
def admin():
    return render_template('admin.html')

if __name__ == '__main__':
    lineDict = read_line()
    app.run(host='0.0.0.0', port=5000)
